package com.pizidea.imagepicker.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.core.content.res.TypedArrayUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.mobilecomps.R;
import com.efounder.util.ToastUtil;
import com.pizidea.imagepicker.ui.activity.ShowProofActivity;

import org.angmarch.views.FlowPathView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;


/***
 * create by meijun
 */
public class ItemFragment extends Fragment implements AdapterView.OnItemClickListener {

    static String[] title = {"低压票办理 ", "选择工具及材料", "签到", "施工前准备", "施工中", "签退", "所长审核"};

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private ListView listview;
    private int flag = -1;
    private EFDataSet mResult;


    ArrayList items = new ArrayList();

    public ItemFragment() {
    }

    public static ItemFragment newInstance(EFRowSet efRowSet) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();


        if(efRowSet!=null){
            String node_tag_name = efRowSet.getString("NODE_TAG_NAME", "");

            for (int i =0;i<title.length;i++){
                title[i].equals(node_tag_name);
                args.putString(ARG_PARAM1, String.valueOf(i));
                break;
            }
            fragment.setArguments(args);
        }


        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

            if (!TextUtils.isEmpty(mParam1)) {
                flag = Integer.parseInt(mParam1);
            }
        }
    }


    BaseAdapter adapter = null;


    private static final String TAG = "ItemFragment";

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {

        final View root = inflater.inflate(R.layout.fragment_item_mj, container, false);
        listview = (ListView) root.findViewById(R.id.listview);
        listview.setOnItemClickListener(this);


        if (adapter == null) {

            adapter = new BaseAdapter() {

                @Override
                public int getCount() {
                    return title.length;
                }

                @Override
                public Object getItem(int position) {
                    return null;
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    ViewHold holder = null;
                    if (convertView == null) {
                        convertView = inflater.inflate(R.layout.item_mj, null);
                        holder = new ViewHold(convertView);
                        convertView.setTag(holder);
                    }
                    holder = (ViewHold) convertView.getTag();
                    if (flag != -1) {
                        if (flag == position) {
                            holder.stick.setDotColor(Color.RED);
                            holder.tv.setTextColor(Color.RED);
                        } else {
                            holder.stick.setDotColor(Color.parseColor("#FF018877"));
                            holder.tv.setTextColor(Color.GRAY);
                        }
                    }
                    //设置右边是否显示附件图片
                    if (items.size() > 0) {
                        //说明已经拿到数据;
                        if (((ArrayList) items.get(position)).size() > 0) {
                            //说明有凭据
                            holder.imageview.setVisibility(View.VISIBLE);
                        } else {
                            holder.imageview.setVisibility(View.INVISIBLE);

                        }
                    }

                    //处理最后一个图片越界问题



                    if(position== title.length-1){
                        holder.stick.setHalfDisplay(1);
                    }else if(position==0){
                        holder.stick.setHalfDisplay(2);
                    }else{
                        holder.stick.setHalfDisplay(3);

                    }

                    holder.tv.setText(title[position]);

                    return convertView;
                }
            };

        }
        listview.setAdapter(adapter);

        GetTaskDataAsyncTask getTaskDataAsyncTask = new GetTaskDataAsyncTask(this.getContext());
        getTaskDataAsyncTask.execute();
        return root;


    }

    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


        //找到对应的附件;

        if (mResult == null) {
            return;
        }
        ArrayList value = (ArrayList) items.get(i);

        //全部走完说明不存在附件;
        if (value != null && value.size() > 0) {
            Intent intent = new Intent(this.getContext(), ShowProofActivity.class);
            intent.putStringArrayListExtra("value", value);

            startActivity(intent);

        } else {

            ToastUtil.showToast(this.getContext(), "没有附件");
        }

    }

    @NonNull
    private ArrayList<String> findProof(int i) {
        List<ESPRowSet> rowSetList = mResult.getRowSetList();
        boolean ext_str = false;
        ArrayList<String> value = new ArrayList<String>();
        for (int j = 0; j < rowSetList.size(); j++) {
            EFRowSet espRowSet = (EFRowSet) rowSetList.get(j);
            Map<String, Object> dataMap = espRowSet.getDataMap();
            ext_str = String.valueOf(dataMap.get("EXT_STR01")).trim().equals("0" + (i + 1));
            if (ext_str) {
                //联网拿数据;
                //拿到四个字段;

                String f_name = (String) dataMap.get("F_NAME");
                String f_guid = (String) dataMap.get("F_GUID");
                String f_path = (String) dataMap.get("F_PATH");
                String f_orde = (String) dataMap.get("F_ORDE");


                value.add(f_name + "&&" + f_guid + "&&" + f_path + "&&" + f_orde);
            }
        }
        return value;
    }


    public static class ViewHold {
        public TextView tv;
        public ImageView imageview;
        //这个view是为了解决最后一个item显示不正确
        public FlowPathView stick;
        public FrameLayout frameLayout;

        public ViewHold(View view) {
           // dot = view.findViewById(R.id.dot);
            tv = (TextView) view.findViewById(R.id.textview);
            imageview = (ImageView) view.findViewById(R.id.file);
           stick = (FlowPathView)view.findViewById(R.id.stick);
          //  frameLayout = (FrameLayout) view.findViewById(R.id.framelayout);
        }


    }

    /*
         * 内部AsyncTask类
         */
    class GetTaskDataAsyncTask extends AsyncTask<String, Integer, EFDataSet> {
        private Context mContext;
        long time = System.currentTimeMillis();


        public GetTaskDataAsyncTask(Context context) {
            this.mContext = context;


        }

        // 进度显示
        protected void onPreExecute() {
            // 进度显示
            super.onPreExecute();
            LoadingDataUtilBlack.show(mContext);
        }

        @Override
        protected EFDataSet doInBackground(String... params) {

            EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

            EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
            EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
            EAI.Path = "OSPMobile";
            EAI.Service = "Android";
            JParamObject PO = JParamObject.Create();


            PO.setEnvValue("DBNO", EnvironmentVariable.getProperty("sign"));// 数据标示
            PO.setEnvValue("Product", EnvironmentVariable.getProperty(KEY_SETTING_APPID));// 服务名称

            // 防止盗用
            PO.setEnvValue(KEY_SETTING_APPID, "PGYDYYM");

            // 权限管理
            PO.SetValueByParamName("LOAD_GNQX", "1");
            JParamObject.assign(PO);
            JResponseObject RO = null;
            EFDataSet flowTaskDataSet = null;

            PO.SetValueByParamName("F_GUID", "g346D1AF_DB7B_4D5D_8BBE_5F4703AB370E");

            try {
                RO = EAI.DAL.SVR("LoadAffixServicePlugin", PO);
            } catch (Exception e) {

            }
            if (RO != null)
                flowTaskDataSet = (EFDataSet) RO.getResponseObject();
            //http://mobile.osp.cloud/OSPMobile/CtrlService?action=loadFile&fwk=FormAffixService&iom=loadAffixData&PO=DataBaseName=ZYYT_DB01;DBNO=ZYHYGL01&FileName=diyapiao2446.png&GUID=g346D1AF_DB7B_4D5D_8BBE_5F4703AB370E&ORDE=2446&MDLID=GDPGModel&affixTable=SYS_MDL_AFFIX_GDPGModel&affixTableB=SYS_MDL_AFFIXB_GDPGModel&CCLX=FILE&PATH=Image/g346D1AF_DB7B_4D5D_8BBE_5F4703AB370E/diyapiao2446.png&SWF_FILE=0&PDF_FILE=0&WJLX=2&AFFIX_WHERE=&F_FLFCT=&F_FLBH=

            return flowTaskDataSet;
        }

        // 当后台操作结束时，此方法将会被调用，计算结果将做为参数传递到此方法中，直接将结果显示到UI组件上
        protected void onPostExecute(EFDataSet result) {

            LoadingDataUtilBlack.dismiss();
            if (result == null) {
                return;
            }
            mResult = result;
            for (int i = 0; i < title.length; i++) {
                items.add(findProof(i));

            }
            adapter.notifyDataSetChanged();
            System.out.println(".....");
        }
    }

}


